package com.usian.service;

import com.usian.mapper.TbItemCatMapper;
import com.usian.pojo.TbItemCat;
import com.usian.pojo.TbItemCatExample;
import com.usian.utils.CatNode;
import com.usian.utils.CatResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ItemcategoryService {

    @Autowired
    private TbItemCatMapper tbItemCatMapper;

  /*  @Autowired
    private RedisClient redisClient;*/
    /**
     * 根据分类 ID 查询子节点
     */
    public List<TbItemCat> selectItemCategoryByParentId(Long id) {
        return tbItemCatMapper.selectItemCategoryByParentId(id);
    }


    /**
     * 查询首页商品分类
     */
    public  CatResult selectItemCategoryAll(){
        CatResult catResult = new CatResult();
        //查询商品分类
        catResult.setData(getCatList(0L));
        return catResult;
    }
        //私有方法，查询商品分类

    private List<?> getCatList(long parentId) {
        TbItemCatExample example = new TbItemCatExample();
        TbItemCatExample.Criteria criteria = example.createCriteria();
        criteria.andParentIdEqualTo(parentId);
        List<TbItemCat> list = this.tbItemCatMapper.selectByExample(example);
        List resultList = new ArrayList();
        int count = 0;
        for(TbItemCat tbItemCat:list){
            //判断是否是父节点
            if(tbItemCat.getIsParent()){
                CatNode catNode = new CatNode();
                catNode.setName(tbItemCat.getName());
                catNode.setItem(getCatList(tbItemCat.getId()));//查询子节点
                resultList.add(catNode);
                count++;
                //只取商品分类中的 18 条数据
                if (count == 18){
                    break;// 结束循环 continue; 结束本次循环 return; 结束当前方法
                }
            }else{
                resultList.add(tbItemCat.getName());
            }
        }
        return resultList;
    }
}
